package com.wnxy.interceptors;

import com.wnxy.utils.UserTokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //检查登录状态,如果未登录那就重定向到登录页去
        String accountFromRequest = UserTokenUtil.getUserAccount(request);
        if (StringUtils.isEmpty(accountFromRequest)){

            String xmlHttpRequestHeader = request.getHeader("x-requested-with");
            if (StringUtils.isEmpty(xmlHttpRequestHeader)){
                //同步请求
                response.sendRedirect("/login.html");

            }else {
                //异步请求
                response.getWriter().write("toLogin");
            }

            return false;
        }

        return true;
    }
}
